package com.jinzhi.api.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.api.service.AuntHomeService;
import com.jinzhi.common.constants.ConstMessages;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.CustomBeanUtils;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.service.UserService;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.dao.JazAuntRefereeDao;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.vo.AuntUserVO;
import com.jinzhi.jzweb.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: mcf
 * @CreateTime: 2024/05/11
 * @Description: 阿姨端首页 impl
 */
@Service
public class AuntHomeServiceImpl implements AuntHomeService {

    private final JazUserDemandService jazUserDemandService;

    private final JazSysProjectService jazSysProjectService;

    private final UserService userService;

    private final JazUserAuntService jazUserAuntService;

    private final JazUserOrderService jazUserOrderService;

    private final JazAuntRefereeDao jazAuntRefereeDao;

    private final JazSysLabelService jazSysLabelService;

    private final JazInterviewService jazInterviewService;

    private final JazMessageService jazMessageService;

    // 用来匹配18位身份证的正则表达式
    // 这里没有包含完整的校验逻辑，只是简单地匹配格式
    private static final Pattern IDCARD_PATTERN = Pattern.compile("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");

    //手机号校验正则
    private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile("^1(([3][0-9])|([4][014-9])|([5][0-35-9])|([6][2567])|([7][0-8])|([8][0-9])|([9][0-35-9]))[0-9]{8}$");

    public AuntHomeServiceImpl(JazUserDemandService jazUserDemandService, JazSysProjectService jazSysProjectService,UserService userService,JazUserAuntService jazUserAuntService,
                               JazUserOrderService jazUserOrderService,JazAuntRefereeDao jazAuntRefereeDao,JazSysLabelService jazSysLabelService,JazInterviewService jazInterviewService,
                               JazMessageService jazMessageService){
        this.jazUserDemandService = jazUserDemandService;
        this.jazSysProjectService = jazSysProjectService;
        this.userService = userService;
        this.jazUserAuntService = jazUserAuntService;
        this.jazUserOrderService = jazUserOrderService;
        this.jazAuntRefereeDao = jazAuntRefereeDao;
        this.jazSysLabelService = jazSysLabelService;
        this.jazInterviewService = jazInterviewService;
        this.jazMessageService = jazMessageService;
    }

    /**
     * 需求分页列表查询
     * @param projectId
     * @param age
     * @param salary
     * @param current
     * @param size
     * @return
     */
    @Override
    public Result<?> selUserDemandList(String projectId, String age, String salary, int current, int size) {
        Page<JazUserDemandDO> page = new Page<JazUserDemandDO>(current, size);
        EntityWrapper<JazUserDemandDO> wrapper=new EntityWrapper<JazUserDemandDO>();
        wrapper.eq("audit_status",1); //已审核
        wrapper.eq("audit_result",0); //已通过
        wrapper.eq("show_status",0); //展示
        wrapper.eq("is_sign",0);//未签约
        if (StringUtil.notEmpty(projectId)){
            wrapper.eq("project_id",projectId);
        }
        if (StringUtil.notEmpty(age)){
            wrapper.eq("age",age);
        }
        if (StringUtil.notEmpty(salary)){
            /** 暂定 */
            if (salary.equals("1")){ // 5000 - 7000
                wrapper.ge("salary",5000).and().le("salary",7000);
            }
            if (salary.equals("2")){ // 7000 - 9000
                wrapper.ge("salary",7000).and().le("salary",9000);
            }
            if (salary.equals("3")){ // > 9000
                wrapper.gt("salary",5000);
            }
        }
        wrapper.orderBy("level",true).orderBy("create_time",false);
        Page<JazUserDemandDO> jazUserDemandDOPage = jazUserDemandService.selectPage(page, wrapper);
        for (int i =0;i<jazUserDemandDOPage.getRecords().size();i++){
            JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazUserDemandDOPage.getRecords().get(i).getProjectId()); //查询服务项目表
            jazUserDemandDOPage.getRecords().get(i).setProjectName(jazSysProjectDO.getName());
            UserDO userDO = userService.selectById(jazUserDemandDOPage.getRecords().get(i).getSysUserid());
            if(null!=userDO && null!=userDO.getIdCardAddress()){
                jazUserDemandDOPage.getRecords().get(i).setIdCardAddress(userDO.getIdCardAddress());
            }

        }

        return Result.ok(jazUserDemandDOPage);
    }

    /**
     * 月嫂入驻功能 阿姨招募提交接口
     * @param auntUserVO
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @Override
    @Transactional
    public Result<?> savaUserAunt(AuntUserVO auntUserVO) throws InvocationTargetException, IllegalAccessException, IntrospectionException {

        //校验身份证
        if(null!=auntUserVO.getIdNumber() && !auntUserVO.getIdNumber().equals("")){
            if (!validateIDCard(auntUserVO.getIdNumber())) {
                return Result.fail("身份证："+auntUserVO.getIdNumber()+"格式错误");
            }
            //获取出生年月
            auntUserVO.setBirthDate(extractBirthdate(auntUserVO.getIdNumber()));
        }
        //校验银行卡号
        if(null!=auntUserVO.getBankCard() && !auntUserVO.getBankCard().equals("")){
            if(auntUserVO.getBankCard().length()!=16 && auntUserVO.getBankCard().length()!=19){
                return Result.fail("银行卡号："+auntUserVO.getBankCard()+"格式错误");
            }
        }
        //校验手机号
        if(null!=auntUserVO.getOrderPhone() && !auntUserVO.getOrderPhone().equals("")){
            if (!validatePhoneNumber(auntUserVO.getOrderPhone())) {
                return Result.fail("电话号码："+auntUserVO.getOrderPhone()+"格式错误");
            }
        }



        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());
//        UserDO userDO = userService.selectById(1800352190213079042L);
        Long userId = userDO.getId();
        //给user表赋值
        CustomBeanUtils.copyNonNullProperties(auntUserVO, userDO);
        userDO.setId(userId);

        JazUserAuntDO jazUserAuntDO =new JazUserAuntDO();//构建月嫂表
        CustomBeanUtils.copyNonNullProperties(auntUserVO,jazUserAuntDO); //进行对象拷贝
        jazUserAuntDO.setId(null);

        jazUserAuntDO.setSysUserid(userDO.getId());//与用户id绑定
        jazUserAuntDO.setCreateTime(new Date()); //创建时间
        jazUserAuntDO.setShowStatus(0); //默认展示状态
        jazUserAuntDO.setSigningStatus(0); //默认未签约状态
        jazUserAuntDO.setAuditStatus(0); //默认待审核状态


        userService.updateById(userDO);

        Long auntId = null;

        EntityWrapper<JazUserAuntDO> wrapper = new EntityWrapper<JazUserAuntDO>();
        wrapper.eq("sys_userid",userDO.getId());
        JazUserAuntDO userAuntDO = jazUserAuntService.selectOne(wrapper); //查询该用户是否已经申请入驻
        if (userAuntDO!=null){ //表明已经入驻了需要修改月嫂信息
            auntId = userAuntDO.getId();
            CustomBeanUtils.copyNonNullProperties(jazUserAuntDO,userAuntDO);
            userAuntDO.setUpdateTime(new Date());
            userAuntDO.setAuditResult(null);

            //查询待开始订单数量
            EntityWrapper<JazUserOrderDO> dkswrapper = new EntityWrapper<JazUserOrderDO>();
            dkswrapper.eq("initiate_id",userDO.getId()).or().eq("signing_id",userDO.getId());
            dkswrapper.andNew().eq("status",0);
            List<JazUserOrderDO> dksjazUserOrderDOS = jazUserOrderService.selectList(dkswrapper);
            if (dksjazUserOrderDOS!=null){
                if (dksjazUserOrderDOS.size() > 0) {
                    return Result.fail("有待开始的订单无法修改");
                }
            }

            //查询待开始订单数量
            EntityWrapper<JazUserOrderDO> jxzwrapper = new EntityWrapper<JazUserOrderDO>();
            jxzwrapper.eq("initiate_id",userDO.getId()).or().eq("signing_id",userDO.getId());
            jxzwrapper.andNew().eq("status",1);
            List<JazUserOrderDO> jxzjazUserOrderDOS = jazUserOrderService.selectList(jxzwrapper);
            if (jxzjazUserOrderDOS!=null){
                if (jxzjazUserOrderDOS.size() > 0) {
                    return Result.fail("有进行中的订单无法修改");
                }
            }
            jazUserAuntService.updateById(userAuntDO);
        }else {
            jazUserAuntService.insert(jazUserAuntDO);
            auntId = jazUserAuntDO.getId();
            //新增阿姨推荐信息
            JazAuntRefereeDO jazAuntRefereeDO = new JazAuntRefereeDO();
            jazAuntRefereeDO.setAuntName(auntUserVO.getName());
            jazAuntRefereeDO.setAuntPhone(auntUserVO.getOrderPhone());
            jazAuntRefereeDO.setRefereeId(auntUserVO.getRefereeId());
            jazAuntRefereeDO.setAuntId(userDO.getId());
            jazAuntRefereeDao.insert(jazAuntRefereeDO);
        }


        //需要重新审核，给阿姨发送一条消息
        JazMessageDO jazMessageDO = new JazMessageDO();
        jazMessageDO.setMessageType(1);
        jazMessageDO.setMessageContent(MessagesEnum.MESSAGE_104.getMsg());
        jazMessageDO.setMessageNum(MessagesEnum.MESSAGE_104.getNum());
        jazMessageDO.setSenderId(userId);
        jazMessageDO.setReceiverId(userId);
        jazMessageDO.setAuntId(auntId);
        jazMessageService.senMessage(jazMessageDO);

        return Result.ok();
    }

    /**
     * 需求详情查询
     * @param id
     * @return
     */
    @Override
    public Result<?> selUserDemandById(String id) {
        JazUserDemandDO jazUserDemandDO = jazUserDemandService.selectById(id);
        jazUserDemandDO.setSex(jazUserDemandDO.getSex().equals("1")?"男":"女");
        jazUserDemandDO.setResidentHome(jazUserDemandDO.getResidentHome().equals("1")?"否":"是");
        if(null!=jazUserDemandDO.getAge()){
            if (jazUserDemandDO.getAge().equals("1")){
                jazUserDemandDO.setAge("35岁以下");
            }else if (jazUserDemandDO.getAge().equals("2")){
                jazUserDemandDO.setAge("36-40岁");
            }else if (jazUserDemandDO.getAge().equals("3")){
                jazUserDemandDO.setAge("41-45岁");
            }else if (jazUserDemandDO.getAge().equals("4")){
                jazUserDemandDO.setAge("50岁以上");
            }
        }
        JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazUserDemandDO.getProjectId()); //查询服务项目表
        jazUserDemandDO.setProjectName(jazSysProjectDO.getName());


        UserDO userDO = userService.selectById(jazUserDemandDO.getSysUserid());
        if(userDO!=null){
            String userName = "";
            if (null !=userDO.getName() && !userDO.getName().equals("")){
                userName = userDO.getNickname();
            }else {
                userName = userDO.getMobile();
            }
            jazUserDemandDO.setUserName(userName);
        }

        return Result.ok(jazUserDemandDO);
    }

    /**
     * 审核状态查询
     * @return
     */
    @Override
    public Result<?> isUserAunt() {
        Map map =new HashMap();
        map.put("status",0); //审核状态：0待审核 1已经通过 2未通过
        map.put("msg","待审核");

        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());

        EntityWrapper<JazUserAuntDO> wrapper = new EntityWrapper<JazUserAuntDO>();
        wrapper.eq("sys_userid",userDO.getId());

        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(wrapper);
        if (jazUserAuntDO == null){
            return Result.ok("还未进行入驻");
        }

        if (jazUserAuntDO.getAuditStatus() == 1){  //表示已经进行审核了
            if (jazUserAuntDO.getAuditResult()==0){
                map.put("status",1); //已通过
                map.put("msg","审核通过");
            }else {
                map.put("status",2); //未通过
                map.put("msg",jazUserAuntDO.getRefuseReason());
            }
        }
        return Result.ok(map);
    }

    /**
     * 判断是否签约
     * @param auntUserId
     * @return
     */
    @Override
    public Result<?> isContract(String auntUserId,Long senderId,Long receiverId,Long objectId) {
        JazUserOrderDO jazUserOrderDO = new JazUserOrderDO();

        //判断是否已经接单
        List<JazMessageDO> jazMessageDOS = jazMessageService.selectList(new EntityWrapper<JazMessageDO>().eq("sender_id", senderId).eq("receiver_id", receiverId).eq("message_type", 2).eq("demand_id", objectId));
        if(jazMessageDOS!=null && !jazMessageDOS.isEmpty()){
            jazUserOrderDO.setHasTaking(true);
        }
        return Result.ok(jazUserOrderDO);
    }

    /**
     * 月嫂信息回显
     * @return
     */
    @Override
    public Result<?> selUserAunt() {
        Long userId = JWTUtil.getUser().getId();
//        Long userId = 1504759468294201346L;
        UserDO userDO = userService.selectById(userId);
        AuntUserVO auntUserVO =new AuntUserVO();
        auntUserVO.setSysUserid(String.valueOf(userDO.getId()));
        AuntUserVO rstAuntUserVO = jazUserAuntService.selAuntUserOne(auntUserVO);
        return Result.ok(rstAuntUserVO);
    }

    /**
     * 可用标签下拉框查询
     * @return
     */
    @Override
    public Result<?> sleLabel() {
        EntityWrapper<JazSysLabelDO> wrapper = new EntityWrapper<JazSysLabelDO>();
        wrapper.eq("status",0);//查询未禁用的标签
        List<JazSysLabelDO> sysLabelDOS = jazSysLabelService.selectList(wrapper);
        return Result.ok(sysLabelDOS);
    }

    /**
     * 阿姨取消或者同意邀约
     * @param jazInterviewDO
     */
    @Transactional
    @Override
    public void cancelInterview(JazInterviewDO jazInterviewDO) {
        Long userId = JWTUtil.getUser().getId();
        EntityWrapper entityWrapper =new EntityWrapper();
        entityWrapper.eq("sys_userid",userId);
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(entityWrapper);
        Assert.notNull(jazInterviewDO.getId(),"参数：id不能为空");
        Assert.notNull(jazInterviewDO.getInterStatus(),"参数：interStatus不能为空");
        jazInterviewService.updateById(jazInterviewDO);

        JazInterviewDO jazInterviewDO1 = jazInterviewService.selectById(jazInterviewDO);

        //发送消息
        JazMessageDO jazMessageDO = new JazMessageDO();
        jazMessageDO.setSenderId(jazInterviewDO1.getInviteeId());
        jazMessageDO.setReceiverId(jazInterviewDO1.getInviterId());
        jazMessageDO.setMessageType(2);
        jazMessageDO.setDemandId(null!=jazInterviewDO1.getDemandId()?jazInterviewDO1.getDemandId():null);
        jazMessageDO.setInterviewId(jazInterviewDO1.getId());
        jazMessageDO.setAuntId(jazUserAuntDO.getId());
        if(jazInterviewDO1.getInterStatus()==1){
            jazMessageDO.setMessageContent(MessagesEnum.MESSAGE_202.getMsg());
            jazMessageDO.setMessageNum(MessagesEnum.MESSAGE_202.getNum());
            jazMessageDO.setHasSendSms(true); //发送短信
        }else {
            jazMessageDO.setMessageContent(MessagesEnum.MESSAGE_203.getMsg());
            jazMessageDO.setMessageNum(MessagesEnum.MESSAGE_203.getNum());
        }
        jazMessageService.senMessage(jazMessageDO);
    }

    /**
     * 我要接单
     * @param senderId
     * @param receiverId
     * @param objectId
     * @return
     */
    @Override
    public Result<?> takingOrders(Long senderId, Long receiverId, Long objectId) {
        //不能重复接单
//        List<JazMessageDO> jazMessageDOS = jazMessageService.selectList(new EntityWrapper<JazMessageDO>().eq("sender_id", senderId).eq("receiver_id", receiverId).eq("message_type", 1).eq("object_id", objectId));
//        if(jazMessageDOS!=null || !jazMessageDOS.isEmpty()){
//            return Result.fail("不能重复接单！");
//        }
        Long userId = JWTUtil.getUser().getId();
        //查询需求的服务类型
        JazUserDemandDO jazUserDemandDO = jazUserDemandService.selectById(objectId);
        if(jazUserDemandDO == null || jazUserDemandDO.getProjectId() == null){
            return Result.fail("数据异常，请联系管理员！");
        }
        //查询月嫂信息服务类型
        JazUserAuntDO jazUserAuntDO1 = jazUserAuntService.selectOne(new EntityWrapper<JazUserAuntDO>().eq("sys_userid", userId));
        if(jazUserAuntDO1==null || jazUserAuntDO1.getProjectId()==null){
            return Result.fail("请先完成简历中的服务类型，再来接单！");
        }

        //判断阿姨是否能简单（阿姨的服务类型必须包含需求的服务类型）
        if(!jazUserAuntDO1.getProjectId().contains(jazUserDemandDO.getProjectId().toString())){
            return Result.fail("您不是此类型阿姨不能接该订单，需要认证审核后才能接单，如有问题可与客服沟通");
        }


        JazMessageDO jazMessageDO = new JazMessageDO();
        jazMessageDO.setSenderId(senderId);
        jazMessageDO.setReceiverId(receiverId);
        jazMessageDO.setMessageType(2);
        jazMessageDO.setDemandId(objectId);
        EntityWrapper entityWrapper =new EntityWrapper();
        entityWrapper.eq("sys_userid",userId);
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(entityWrapper);
        jazMessageDO.setAuntId(jazUserAuntDO.getId());
        jazMessageDO.setMessageContent(MessagesEnum.MESSAGE_101.getMsg());
        jazMessageDO.setMessageNum(MessagesEnum.MESSAGE_101.getNum());
        jazMessageDO.setHasSendSms(true); //发短信
        jazMessageService.senMessage(jazMessageDO);
        return Result.ok();
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    @Override
    public Result<?> getUserInfo(String token) {
        if(StringUtils.isBlank(token)){

            return Result.fail("未登录！");
        }
        //调用jwt工具类的方法，根据request对象获取头信息，返回对象id
//        if(redisUtil.get(token)==null){
//            return ApiResult.fail("用户不存在");
//        }
        // String userid=  redisUtil.get(token).toString();;
        //查询数据库根据用户id获取用户数据
        UserDO member = userService.selectById(JWTUtil.getUser().getId());

        if(member==null){
            return Result.fail("用户不存在");
        }

        return Result.ok(member);
    }

    /**
     * 判断阿姨招募是否能填写
     * true:可以
     * false:不可以
     * @return
     */
    @Override
    public Result<?> getIsEdit(Long auntId) {
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectById(auntId);
        if(jazUserAuntDO!=null && jazUserAuntDO.getSysUserid()!=null){
            UserDO userDO = userService.selectById(jazUserAuntDO.getSysUserid());
            if(userDO!=null && userDO.getName()!=null && userDO.getOrderPhone()!=null && jazUserAuntDO.getProjectId()!=null && userDO.getEducation()!=null
                    && jazUserAuntDO.getDutyTime()!=null && jazUserAuntDO.getWorkExperience()!=null && jazUserAuntDO.getResidentHome()!=null){
                return Result.ok(false);
            }
        }

        return Result.ok(true);
    }


    /**
     * 身份证校验
     * @param idCard
     * @return
     */
    public  boolean validateIDCard(String idCard) {
        Matcher matcher = IDCARD_PATTERN.matcher(idCard);
        return matcher.matches();
    }

    public  boolean validatePhoneNumber(String orderPhone) {
        Matcher matcher = PHONE_NUMBER_PATTERN.matcher(orderPhone);
        return matcher.matches();
    }

    /**
     * 截取出生年月
     * @param idCard
     * @return
     */
    public  String extractBirthdate(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            return null;
        }
        // 截取出生年月日（第7位到第14位）
        return idCard.substring(6, 10) + "-" + idCard.substring(10, 12) +"-"+ idCard.substring(12, 14);
    }

}
